//
//  IconMessageAlert.swift
//  SCA
//
//  Created by tjun on 2025/9/20.
//

import UIKit

class IconMessageAlert: UIViewController {
    
    enum IconType: String {
      case succeed = "alert_succeed"
      case error = "alert_error"
      case warn = "alert_warn"
    }
    
    private var maskView: UIButton!
    private var contentView: UIView!
    
    let messsage: String
    let iconType: IconType
    let isHtmlMessage: Bool
    var onDismiss: (() -> Void)?
    
    init(messsage: String, iconType: IconType, isHtmlMessage: Bool = false, onDismiss: (() -> Void)? = nil) {
        self.messsage = messsage
        self.iconType = iconType
        self.isHtmlMessage = isHtmlMessage
        self.onDismiss = onDismiss
        super.init(nibName: nil, bundle: nil)
        modalPresentationStyle = .custom
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func showIn(_ controller: UIViewController) {
        controller.present(self, animated: false, completion: nil)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        view.backgroundColor = .clear
        
        maskView = UIButton(frame: view.bounds).addTo(view)
        maskView.backgroundColor = .black.withAlphaComponent(0)
        
        let contentW = view.width - 110
        var contentH: CGFloat = 350
        
        contentView = UIView().addTo(view)
        contentView.backgroundColor = UIColorMake(0x212529)
        contentView.frame = CGRectMake((view.width - contentW) * 0.5, -contentH , contentW, contentH)
        contentView.addCorner(radius: 15)
        
        let iconImageView = UIImageView(image: UIImage(named: iconType.rawValue))
        iconImageView.addTo(contentView)
        iconImageView.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(34)
        }
        
        let textLabel = UILabel(textColor: .white, textAlignment: .center).addTo(contentView)
        textLabel.numberOfLines = 0
                  
        if isHtmlMessage {
            if let data = messsage.data(using: .utf8) {
                
                let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [
                    .documentType: NSAttributedString.DocumentType.html,
                    .characterEncoding: String.Encoding.utf8.rawValue
                ]
                
                if let attributedText = try? NSMutableAttributedString(data: data, options: options, documentAttributes: nil) {
                    let fullRange = NSRange(location: 0, length: attributedText.length)
                    attributedText.addAttributes([
                        .font: UIFont.systemFont(ofSize: 16, weight: .medium),
                        .foregroundColor: UIColor.white,
                    ], range: fullRange)
                    
                    textLabel.attributedText = attributedText
                }
            }
        } else {
            textLabel.attributedText =  messsage.titleMargin(3, font: UIFontMediumMake(16), alignment: .center)
        }
      
        textLabel.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(AppStyle.margin.left)
            make.top.equalTo(iconImageView.snp.bottom).offset(25)
        }
        
        let confirmButton = MainButton(type: .system, title: "OK", font: UIFontMake(16), textColor: .white)
        confirmButton.addTo(contentView)
        confirmButton.addCorner(radius: 10)
        confirmButton.addTarget(self, action: #selector(confirmButtonTapped), for: .touchUpInside)
        confirmButton.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.width.equalTo(148.scaled)
            make.height.equalTo(AppStyle.size.smallButtonHeight.scaled)
            make.top.equalTo(textLabel.snp.bottom).offset(35)
        }
        
        view.setNeedsLayout()
        view.layoutIfNeeded()

        contentH = CGRectGetMaxY(confirmButton.frame) + 30
        contentView.frame = CGRectMake((view.width - contentW) * 0.5, (view.height - contentH) * 0.5 - 35 , contentW, contentH)
    }
     
    @objc func confirmButtonTapped() {
        dismiss(completion: onDismiss)
    }
 
    private func dismiss(completion: (() -> Void)? = nil) {
        UIView.animate(withDuration: 0.1) {
            self.maskView.backgroundColor = .black.withAlphaComponent(0)
        }
        self.dismiss(animated: false, completion: completion)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
 
        self.contentView.layer.transform = CATransform3DMakeScale(0.6, 0.6, 0.6)
        self.contentView.alpha = 0.5
        UIView.animate(withDuration: 0.25, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.8, options: .curveEaseIn) {
            self.contentView.alpha = 1
            self.maskView.backgroundColor = .black.withAlphaComponent(0.5)
            self.contentView.layer.transform = CATransform3DMakeScale(1, 1, 1)
        }
    }
    
    
}

